import type { Dayjs } from 'dayjs'
import { type CalendarProps } from '.'
import dayjs from 'dayjs'
import cs from 'classnames'

interface MonthCalendar extends CalendarProps {}

interface DaysInfo {
  date: Dayjs
  isCurrentMonth: boolean
}
/**
 * 获取基于传递日期算出来的，日历上要显示的所有日期的dayjs对象
 * @param date
 * @returns
 */
function getAllDays(date: Dayjs): DaysInfo[] {
  const days = new Array(6 * 7) //以这个数据结构为假设进行排列日期
  const startDate = date.startOf('month') //获取这个月的第一天
  const day = startDate.day() //获取这天在对应周的下标（即从0~6开始算起）
  //开始循环搞事先得到之前的日期的信息

  for (let i = 0; i < day; i++) {
    const cloneDate = startDate.subtract(day - i, 'day') //返回减去指定量的dayjs对象
    const item = {
      date: cloneDate,
      isCurrentMonth: date.month() === cloneDate.month() //这里可以直接写false,肯定不是这个月的
    }
    days[i] = item
  }

  //得到后面的所以的日期
  for (let i = day; i < days.length; i++) {
    const cloneDate = startDate.add(i - day, 'day') //返回增加指定量的dayjs对象
    const item = {
      date: cloneDate,
      isCurrentMonth: date.month() === cloneDate.month()
    }
    days[i] = item
  }

  return days
}

function renderDays(allDays: DaysInfo[], value: Dayjs) {
  const rows = []
  for (let i = 0; i < 6; i++) {
    const row = []
    for (let j = 0; j < 7; j++) {
      const item = allDays[i * 7 + j]

      const classNames = cs(
        'calendar-month-body-row-cell',
        item.isCurrentMonth ? 'calendar-month-body-row-cell-current' : ''
      )

      row.push(<div class={classNames}>{item.date.date()}</div>)
    }
    rows.push(row)
  }

  return rows.map((i) => <div class="calendar-month-body-row">{i}</div>)
}

function MonthCalendar(props: MonthCalendar) {
  const { value } = props
  const weeekList = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']

  const allDays = getAllDays(dayjs(Date.now()))

  return (
    <div class="calendar-month">
      <div class="calendar-month-week-list">
        {weeekList.map((i) => (
          <div class="calendar-month-week-list-item">{i}</div>
        ))}
      </div>
      <div class="canlendar-month-body">{renderDays(allDays, value)}</div>
    </div>
  )
}

export default MonthCalendar
